package com.fair.concurrency.example.sync;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/9/23 18:10
 */
public class CyclicBarrierTest
{
    //钢蛋
    static class Person extends Thread
    {
        CyclicBarrier cyclicBarrier;
        String name;

        public Person(CyclicBarrier cyclicBarrier, String name)
        {
            this.cyclicBarrier = cyclicBarrier;
            this.name = name;
        }

        @Override
        public void run()
        {
            System.out.println("钢蛋" + name + "：别打了，大哥，我这个月的零发钱都给你");
            try
            {
                cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e)
            {
                e.printStackTrace();
            }
        }
    }

    static class Sleep extends Thread
    {
        @Override
        public void run()
        {
            System.err.println("打累了，歇会，抽根烟!!!");
        }
    }

    public static void main(String[] args)
    {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Sleep());
        for (int i = 0; i < 5; i++)
        {
            new Person(cyclicBarrier, String.valueOf(i)).start();
        }
        try
        {            //休息1s，再打
            Thread.sleep(1000);
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        for (int i = 0; i < 5; i++)
        {
            new Person(cyclicBarrier, String.valueOf(i)).start();
        }
    }
}
